import * as http from "http";


function getJsonCB(url: string, cb: (e?: Error, result?: object) => void) {
    http.get(url, (res) => {
        //链接状态码
        const {statusCode} = res;
        if (statusCode !== 200) {
            let error = new Error('Request Failed.\n' + `Status Code: ${statusCode}`);
            console.error(`getJson HttpConnection error: ${error.message}`);
            // consume response data to free up memory
            res.resume();
            cb(error);
            return;
        }

        //接受UTF8编码的消息
        res.setEncoding('utf8');
        let rawData = '';
        res.on('data', (chunk) => {
            rawData += chunk;
        });
        res.on('end', () => {
            try {
                cb(undefined, JSON.parse(rawData));
            } catch (e) {
                console.error(`getJson JSON Parse error: ${e.message}`);
                cb(e);
            }
        });
    }).on('error', (e) => {
        console.error(`getJson HttpConnection error: ${e.message}`);
        cb(e);
    });
}

async function getJsonAsync(url: string): Promise<object | Error> {
    return new Promise((resolve, reject) => {
        getJsonCB(url, (e, result) => {
            if (e) reject(e);
            else resolve(result);
        })
    })

}


export {getJsonCB, getJsonAsync}